<template>
  <div>
    <el-row :gutter="30">
      <el-col :sm="24">
        <el-row>
          <el-col :sm="24" class="text-left title ">
            <i class="el-icon-message"></i>&nbsp;【RSocket】WebSocket信息交互
            <div class="block-line">&nbsp;</div>
          </el-col>
        </el-row>
        <el-form ref="form" :model="form" label-width="100px" :rules="rules"
          label-position="right" size="small" :inline-message="true">
          <el-form-item label="消息：" :sm="4" prop="message">
            <el-col :sm="15" style="text-align:left;">
              <el-input v-model="form.message" placeholder="请输入消息内容" suffix-icon="el-icon-info"></el-input>
            </el-col>
            <el-col :sm="4">
              <el-button type="primary" id="sendBut" @click="submitForm">发送</el-button>
            </el-col>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="30">
      <el-col :sm="1">&nbsp;</el-col>
      <el-col :sm="23">
        <p v-for="res in results" :key="res" style="text-align: left; padding: -50;">
          <el-tag type="danger"><i class="el-icon-loading"></i>&nbsp;{{ res }}</el-tag></p>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { RSocketClient } from 'rsocket-core'
import { MAX_STREAM_ID } from 'rsocket-core'
import RSocketWebSocketClient from 'rsocket-websocket-client'
import {mapGetters} from 'vuex'
const websocketUrl = 'ws://localhost:6969/websocket'
const client = new RSocketClient({
  setup: {
    keepAlive: 60000,
    lifetime: 180000,
    dataMimeType: 'application/json',
    metadataMimeType: 'message/x.rsocket.routing.v0'
  },
  transport: new RSocketWebSocketClient({
    url: websocketUrl
  })
})
export default {
  data () {
    return {
      results: [],
      socket: null,
      form: {
        message: ''
      },
      rules: {
        message: [
          { required: true, message: '请输入消息内容', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm () { // 表单提交事件
      this.$refs['form'].validate((valid) => { // 表单验证
        if (valid) { // 验证通过
          this.results = [] // 每次操作前清空数据
          this.socket.requestStream({ // Stream模式
            data: this.form.message, // 请求数据
            metadata: String.fromCharCode('message.repeat'.length) + 'message.repeat' // 消息处理路径
          }).subscribe({ // 数据响应处理
            onError: (e) => console.log(e), // 错误处理
            onNext: (payload) => { // 响应接收
              this.results.push(payload.data) // 数据保存
            },
            onSubscribe: subscription => { // 订阅处理
              subscription.request(MAX_STREAM_ID) // 订阅请求
            }
          })
          this.$refs['form'].resetFields() // 表单重置
        } else {
          return false
        }
      })
    }
  },
  mounted () {
    client.connect().then(socket => {
      this.socket = socket
    })
  },
  computed: {
    ...mapGetters(['apikey'])
  }
}
</script>
<style scoped>
</style>
